/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package my12306;

import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Jack
 */
public class AudioThread extends Thread {

    private final Logger log = LoggerFactory.getLogger(getClass());
    private final Object waitLock = new Object();
    private boolean stop = false;
    private final static String NAME = "AudioThread";
    private AudioClip audio;

    public AudioThread() {
        setName(NAME);
    }

    @Override
    public void run() {
        do {
            try {
                log.info("waiting for signal...");
                waitForSignal();
                if (isStop()) {                    
                    break;
                }
                getAudio().play();
                synchronized (this) {
                    notifyAll();
                }
            } catch (Exception ex) {
                log.error(ex.getLocalizedMessage(), ex);
            }
        } while (!isStop());
    }

    public void play() {
        synchronized (waitLock) {
            log.info("sending signal...");
            waitLock.notifyAll();
            log.info("sending signal... done");
        }
    }

    /**
     * wait signal
     */
    public void waitForSignal() {
        synchronized (waitLock) {
            try {
                waitLock.wait();
            } catch (InterruptedException ie) {
                // continue
            }
        }
    }

    /**
     * set stop signal
     */
    public synchronized void setStop() {
        stop = true;
        play();
    }

    /**
     * @return the stop
     */
    public synchronized boolean isStop() {
        return stop;
    }

    /**
     * @return the audio
     */
    public AudioClip getAudio() {
        if (audio == null) {
            URL url = getClass().getResource("resources/Audio.wav");
            audio = Applet.newAudioClip(url);
        }
        return audio;
    }
}
